import logo from '@/assets/logo.png'
import './index.scss'
import { Form, Input, Button, Checkbox, message } from 'antd'
import { UserOutlined, LockOutlined } from "@ant-design/icons";
import { useDispatch } from "react-redux"
import { loginAction } from "@/store/actions/user"
import { useHistory } from "react-router-dom"

const loginRules = [
    {
        required: true,
        message: "手机号不能为空",
    },
    {
        pattern: /^1[3-9]\d{9}$/,
        message: "手机号格式不正确",
    },
]

const codeRules = [
    {
        required: true,
        message: "验证码不能为空",
    },
    {
        pattern: /^\d{6}$/,
        message: "验证码的格式不正确",
    },
]

const isAgreeRules = [
    {
        validator(rule, value) {
            return value ?
                Promise.resolve()
                : Promise.reject(new Error("您还没有勾选用户协议条款"))
        }
    }
]


const Login = () => {
    const dispatch = useDispatch()
    const history = useHistory()
    const onFinish = async (values) => {
        // 派发action
        try {
            await dispatch(loginAction(values)) // 登录成功 登录失败
            message.success("登录成功")
            // history.replace("/home") // 跳到首页
            history.replace(history.location?.state?.from || "/home")
            // 登录成功
        } catch (error) {
            console.log(error)
            message.error("登录失败")
        }
    }
    return (
        <div className="login">
            <div className="login-container">
                <img className="login-logo" src={logo} alt="" />
                {/* 登录表单 */}
                <Form initialValues={{
                    mobile: "13911111111",
                    code: "246810",
                    isAgree: true
                }} onFinish={onFinish}
                    size="large"
                    validateTrigger="onBlur">
                    <Form.Item name="mobile" rules={loginRules}>
                        <Input prefix={<UserOutlined />} placeholder="请输入手机号" />
                    </Form.Item>
                    <Form.Item name="code" rules={codeRules}>
                        <Input prefix={<LockOutlined />} placeholder="请输入验证码" />
                    </Form.Item>
                    <Form.Item name="isAgree" valuePropName="checked" rules={isAgreeRules}>
                        <Checkbox>我已阅读并同意「用户协议」和「隐私条款」</Checkbox>
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" block htmlType='submit'>
                            登录
                        </Button>
                    </Form.Item>
                </Form>
            </div>
        </div>
    )

}

export default Login